/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2022. All rights reserved.
 */

import { FileUtil } from '../utils/file-util.js';

import { BaseCommandBuilder } from './base-command-builder.js';

export class JavaCommandBuilder extends BaseCommandBuilder {
  private _javaSystemList: string[];

  constructor() {
    super([]);
    this.commandList.push('java');
    this._javaSystemList = [];
  }

  //  index
  addCalledJarFile(jarFile: string): JavaCommandBuilder {
    FileUtil.checkPathLength(jarFile);
    if (1 === this.commandList.length) {
      this.commandList.push('-jar');
      this.commandList.push(jarFile);
    } else {
      const java = this.commandList.slice(0, 1);
      const rest = this.commandList.slice(1);
      this.commandList = [...java, ...['-jar', jarFile], ...rest];
    }
    return this;
  }

  addJvmOption(jvmOption: string): JavaCommandBuilder {
    this.commandList.push(jvmOption);
    return this;
  }

  addClassPath(classpath: string): JavaCommandBuilder {
    FileUtil.checkPathLength(classpath);
    this.commandList.push('-classpath');
    this.commandList.push(classpath);
    return this;
  }

  addMainClass(mainClass: string): JavaCommandBuilder {
    this.commandList.push(mainClass);
    return this;
  }

  build(): string[] {
    // -D属性需要接在java命令行后, 避免被识别为jar包的输入参数
    return [...this.commandList.slice(0, 1), ...this._javaSystemList, ...this.commandList.slice(1)];
  }

  /**
   * 声明java的系统变量, 格式为-D[key]=[value]
   *
   * @param {string} key
   * @param {string} value
   * @returns {JavaCommandBuilder}
   */
  setJavaSystemProperty(key: string, value: string): JavaCommandBuilder {
    this._javaSystemList.push(`-D${key}=${value}`);
    return this;
  }
}
